<template>
  <div id="app">
    <audio id="myaudio" ref="audio" @timeupdate="musicTimeUpdate" @canplay="musicCanPlay" @playing="musicOnPlaying" @ended="musicEnded"
      @waiting="musicOnWaiting" @pause="musicOnPause" @loadstart="loadStart"></audio>

    <!-- 底部显示的浮层页  音乐列表 -->
    <music-list></music-list>

    <!-- 音乐播放详情  显示cd页 -->
    <music-detail></music-detail>

  </div>
</template>

<script>
import musiclist from './../musiclist/musiclist.vue';
import musicdetail from './../musicdetail/musicdetail.vue';
import Vue from 'vue';
import axios from 'axios';
import Vueaxios from 'vue-axios';
import store from './../../store';

Vue.use(Vueaxios, axios)

let musicLrcIndex = 0
export default {
  data () {
    return {
      info: {}
    }
  },
  methods: {
    // 音频播放结束事件
    musicEnded () {
      store.dispatch('play_Ended')
      // 歌词初始化
      musicLrcIndex = 0
      store.commit({
        type: 'setLyricIndex',
        index: 0
      })
    },
    // 音乐播放时间更新事件
    musicTimeUpdate () {
      store.dispatch({
        type: 'set_CurrentTime',
        time: Math.floor(this.$refs.audio.currentTime)
      })

      // 设置歌词内容(以索引的形式显示,主要是)
      let musicLrc = store.getters.getCurrentMusic.lyric
      let currentTime = Math.floor(this.$refs.audio.currentTime)
      if (musicLrc[musicLrcIndex] === undefined) return
      if (musicLrc.length === 0) {
        store.commit({
          type: 'setLyricIndex',
          index: -1
        })
        return;
      }
      for (let i = 0; i < musicLrc.length; i++) {
        if (currentTime >= Number(musicLrc[musicLrcIndex].timeId)) {
          musicLrcIndex += 1
          // return
          break;
        } else {
          if (musicLrcIndex <= 0) {
            musicLrcIndex = 0
          } else {
            musicLrcIndex--
          }
        }
      }
      store.commit({
        type: 'setLyricIndex',
        index: musicLrcIndex
      })
    },
    // 可以播放事件
    musicCanPlay () {
      store.dispatch({
        type: 'set_MusicDuration',
        duration: Math.floor(this.$refs.audio.duration)
      })
      store.commit({
        type: 'setMusicLoadStart',
        isloadstart: false
      })
    },
    // 音乐处于播放状态
    musicOnPlaying () {
      if (this.$store.getters.getCurrentTime === 0) {
        let currentMusic = this.$store.getters.getCurrentMusic
        this.submitplaydetail(
          currentMusic.id,
          new Date().format('yyyyMMddhhmmss')
        )
      }
      // store.commit('play')
    },
    // 音乐处于watting状态
    musicOnWaiting () {
      // alert('音乐加载中')
    },
    // 音乐处于暂停状态
    musicOnPause () {
      // store.commit('pause')
    },
    // 音乐加载
    loadStart () {
      store.commit({
        type: 'setMusicLoadStart',
        isloadstart: true
      })
    },
    getMusicList () {
      axios
        .get(
          this.host +
            `/api/taijiao/getmusic/${
              this.$store.getters.getPageParams.month
            }?openid=${this.$store.getters.getPageParams.openid}`
        )
        .then(
          res => {
            // data.user的信息赋值给info  再通过组件的数据传递传给sideBar
            this.info = res.data.user
            // 把所有的音乐数据给vuex的musicAllList
            let musicList = []
            res.data.map(item => {
              musicList.push({
                id: item.no,
                name: item.name,
                singer: item.author,
                month: this.$store.getters.getPageParams.month,
                img_url: `http://files100.oss-cn-beijing.aliyuncs.com/taijiao/img/${
                  item.no
                }.jpg`,
                url: `http://files100.oss-cn-beijing.aliyuncs.com/taijiao/${
                  item.no
                }.mp3`,
                type: '万点数据',
                lyric: []
              })
            })

            store.dispatch('set_MusicAllList', { all: musicList })
            // 所有的数据存起来  包括音乐个人信息 等等
            //   store.dispatch('set_AllInfo', res.data)
            // 设置音乐的地址  初始化 根据vuex的currentIndex来决定
            this.$refs.audio.setAttribute(
              'src',
              store.getters.getCurrentMusic.url
            )
            // 给audio元素存在vuex 的state里面  方便日后调用
            store.dispatch('set_AudioElement', this.$refs.audio)

            setTimeout(() => {
              store.commit('togglePlay')
            }, 100)
          },
          err => {
            console.error(err)
          }
        )
    },

    /**
     * 这是每首歌开始时的播放明细。点一下首，或者，自动播放时提交一下
     */
    submitplaydetail (musicNo, playStartTime) {
      axios({
        method: 'post',
        url: this.host + '/api/taijiao/submitplaydetail',
        headers: {
          'Content-type': 'application/x-www-form-urlencoded; charset=UTF-8'
        },
        data: this.urlEncode({
          musicNo, //  歌曲ID
          playStartTime, // 播放开始时间
          timeStr: this.$store.getters.getPageParams.timeStr,
          openid: this.$store.getters.getPageParams.openid
        }).replace(/^\&/, '')
      }).then(
        res => {
          // console.log(res)
        },
        err => {
          console.error(err)
        }
      )
    }
  },
  components: {
    // 'menu-list': menulist,
    'music-list': musiclist,
    'music-detail': musicdetail
  },
  created () {
    this.getMusicList()
  }
}
</script>
